package com.llyb.tingshu.search.receiver;

import com.llyb.tingshu.common.rabbit.constant.MqConst;
import com.llyb.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class SearchReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 专辑上架
     * @param albumId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
                    value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true", autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true", autoDelete = "false"),
                    key = MqConst.ROUTING_ALBUM_UPPER )
    )
    public void upper(Long albumId, Message message, Channel channel) {

        try {
            if (albumId!=null) {
                searchService.upperAlbum(albumId);
                log.info("专辑上架成功，专辑id：{}",albumId);
            }
        } catch (Exception e) {
            log.error("专辑上架失败：{}",e.getMessage());
        }

        // 手动确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 专辑下架
     * @param albumId
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM, durable = "true", autoDelete = "false"),
            key = MqConst.ROUTING_ALBUM_LOWER )
    )
    public void lower(Long albumId, Message message, Channel channel) {

        try {
            if (albumId!=null) {
                searchService.lowerAlbum(albumId);
                log.info("专辑下架成功，专辑id：{}",albumId);
            }
        } catch (Exception e) {
            log.error("专辑下架失败：{}",e.getMessage());
        }

        // 手动确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
